<?php

namespace common\utils;

/**
 *
 */
class XML
{

    public static function xmlToArray($xml)
    {
        //禁止引用外部xml实体
        $disableLibxmlEntityLoader = libxml_disable_entity_loader(true);
        $array = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        libxml_disable_entity_loader($disableLibxmlEntityLoader);
        return $array;
    }

    public static function arrayToXml(array $data, $root = true)
    {
        $xml = '';
        if ($root) {
            $xml .= '<xml>';
        }
        foreach ($data as $k => $v) {
            if (is_array($v)) {
                $v = self::arrayToXml($v, false);
            } elseif (!is_numeric($v)) {
                $v = '<![CDATA[' . $v . ']]>';
            }
            $xml .= '<' . $k . '>' . $v . '</' . $k . '>';
        }
        if ($root) {
            $xml .= '</xml>';
        }
        return $xml;
    }

    /**
     * @param array $data
     * @return string
     */
    public static function arrayToXml2(array $data)
    {
        $xml = '';
        foreach ($data as $k => $v) {
            if (is_array($v)) {
                $v = self::arrayToXml2($v);
            }
            $xml .= '<' . $k . '>' . $v . '</' . $k . '>';
        }
        return $xml;
    }

}
